'''
Based on https://github.com/mariusv/Area53
dependencies - boto >= v2.0, area53
'''

import logging
import sys
import os
import re
import urllib2
import ConfigParser

basePath = os.path.realpath(os.path.dirname(sys.argv[0]))

logger = logging.getLogger('zones')
hdlr = logging.FileHandler(basePath + '/example.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) 
logger.setLevel(logging.DEBUG)

logger.info('Zone Script running')

blacklist = []
if os.path.isfile(basePath + '/blacklist.txt'):
    file = open(basePath + '/blacklist.txt','r')
    if file:
        for line in file:
            blacklist.append(line)
            logger.debug('Found blacklist %s' % line)
else:
    logger.debug('No blacklist found')

#get the actual ip address
buffer = urllib2.urlopen('http://wtfismyip.com/text')

results=buffer.read()

ip = re.compile('(([2][5][0-5]\.)|([2][0-4][0-9]\.)|([0-1]?[0-9]?[0-9]\.)){3}'
                +'(([2][5][0-5])|([2][0-4][0-9])|([0-1]?[0-9]?[0-9]))')

#look for an ip address in the response
match = ip.search(results)

stored_ip = ''

if match:

  actual_ip_address = match.group()
  logger.debug('Obtained IP ' + actual_ip_address)

  config = ConfigParser.ConfigParser()

  config.read(basePath + '/config.ini')
        
  key = config.get("aws_keys","key")
  access = config.get("aws_keys","access")
  
  os.environ['AWS_ACCESS_KEY_ID'] = key
  os.environ['AWS_SECRET_ACCESS_KEY'] = access
  
  from area53 import route53
  
  '''
  Iterate through all zones
  '''
  zones = route53.get_zones()
  
  for zone in zones:
    for record in zone.get_records():
      if record.type == 'A':
        if record.resource_records[0] != actual_ip_address:
          logger.info('IP address different (zone %s recordset %s)' % (zone.name,record.name))
          zone.update_a(record.name,actual_ip_address,record.ttl)
          logger.info('Updated to %s' % actual_ip_address)
              
            

  
  
  
  
  

	


